﻿@model List<Product>

@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/_LayoutAdmin.cshtml";
}

<div class="table-responsive">
    @(
 Html.Kendo().Grid(Model).Name("products")
 .Columns(columns =>
 {
     columns.Bound(t => t.Picture).ClientTemplate(string.Format("<img width='30' height='30' src='data:image/jpeg;base64,{0}' />", "${Image64}")).Title("Picture");
     columns.Bound(p => p.ProductName);
     columns.ForeignKey(t => t.CategoryId, (List<Category>)ViewData["categories"], "CategoryId", "CategoryName").Title("Category");
     columns.Bound(p => p.QuantityPerUnit);
     columns.Bound(p => p.UnitPrice);
     columns.Bound(p => p.UnitsInStock);
     columns.Command(command =>
     {
         command.Edit();
         command.Destroy();
     }).Width(180).HtmlAttributes(new { style = "text-align:center;" });
     columns.Bound(p => p.FileContent).ClientTemplate("#= productDetails(data) #").Title("File");
 })
 .ToolBar(toolbar => toolbar.Create())
     .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("Product").Window(w =>
     {
         w.Width(500);
     }))
 .Pageable()
 .Sortable()
 .DataSource(dataSource =>
      dataSource.Ajax()
        .PageSize(10)
        .ServerOperation(false)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ProductId))
        .Create(create => create.Route("Admin", new { action = "EditingPopup_Create", controller = "Product" }))
          //.Read(read => read.Route("Admin", new { action = "EditingPopup_Read", controller = "ProductAdmin" }))
        .Update(update => update.Route("Admin", new { action = "EditingPopup_Update", controller = "Product" }))
        .Destroy(delete => delete.Route("Admin", new { action = "Download", controller = "Product" }))
        )
    )
</div>

<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>

<script>
    function productDetails(product) {

        if (product.FileContent != null) {
            var action = '@Url.Action("Download", "Product")';

            var html = kendo.format("<a href='{0}?productId={1}' class='btn btn-sm btn-primary'>Download</a>",
                action,
                product.ProductId
            );

            return html;
        }

        return "";
    }
</script>

<script type="text/x-kendo-tmpl" id="template">
    <div class="employee">

        <img src="data:image/png;base64,${Picture}" />

        <h3>${ProductName}</h3>


    </div>
</script>
